<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { ElDrawer, ElMessage, ElButton } from 'element-plus'
import SimpleChat from './SimpleChat.vue'
import { stopDifyConfig, stopDifyRequest, stopMessageToDify } from '@/api/dify'
// 接收属性
const props = defineProps({
  apiKey: {
    type: String,
    default: ''
  },
  apiBase: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入您的问题...'
  },
  inputs: {
    type: Object,
    default: () => ({})
  },
  title: {
    type: String,
    default: '智能助手'
  },
  showFloatButton: {
    type: Boolean,
    default: true
  },
  welcomeMessage: {
    type: String,
    default: '你好！我是电费异常识别系统的智能助手，有什么可以帮助您的？'
  },
  minWidth: {
    type: Number,
    default: 400
  },
  maxWidth: {
    type: Number,
    default: 800
  },
  defaultWidth: {
    type: Number,
    default: 600
  }
})

// 定义要向父组件传递的事件
const emit = defineEmits(['message-end', 'json-extracted', 'onFinish', 'before-open'])

// 抽屉是否可见
const drawerVisible = ref(false)

// 抽屉宽度
const drawerWidth = ref(props.defaultWidth)

// 拖拽状态
const isDragging = ref(false)

// 按钮和标题区域高度
const headerHeight = 60

// 计算聊天区域高度
// const chatHeight = computed(() => `calc(100vh - ${headerHeight}px)`)

// 打开抽屉
const openDrawer = () => {
  drawerVisible.value = true
}

// 处理悬浮按钮点击
const handleFloatButtonClick = () => {
  // 触发before-open事件，让父组件有机会处理（如数据验证）
  emit('before-open')
  // 在事件触发后再打开抽屉，父组件如需拦截应在before-open事件中主动调用closeDrawer
  // openDrawer()
}

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false
}

const stopTaskID = ref('') // 分析回调task_id

const handleGetTaskID = (taskID) => {
  stopTaskID.value = taskID
}

// 引用 SimpleChat 组件
const simpleChatRef = ref<InstanceType<typeof SimpleChat> | null>(null)
// 抽屉关闭回调
const handleClose = async () => {
  console.log('=======调用关闭抽屉========')
  console.log('===========simpleChatRef', simpleChatRef)
  if (!stopTaskID.value) {
    // 在关闭抽屉之前调用子组件的 clearConversation 方法
    simpleChatRef.value?.clearConversation('01')
    drawerVisible.value = false // 关闭抽屉
    return
  }
  try {
    // 配置API请求
    const config: stopDifyConfig = {
      apiKey: props.apiKey,
      apiBase: props.apiBase,
      taskID: stopTaskID.value
    }

    // 创建请求对象
    const request: stopDifyRequest = {
      user: 'user-20250515'
    }

    // 直接调用API
    await stopMessageToDify(
      request,
      config,
      (response) => {
        console.log('获取请求结果:', response)
        // 在关闭抽屉之前调用子组件的 clearConversation 方法
        simpleChatRef.value?.clearConversation('01')
        drawerVisible.value = false // 关闭识别结果展示弹窗
      },
      (error) => {
        console.error('停止执行报错:', error)
        ElMessage.error('停止执行报错: ' + (error.message || '未知错误'))
      }
    )
  } catch (error) {
    console.error('停止执行报错:', error)
    ElMessage.error('停止执行报错，请重试')
  }
}

// 传递事件到父组件
const handleMessageEnd = (result) => {
  emit('message-end', result)
}

const handleJsonExtracted = (data) => {
  emit('json-extracted', data)
}

const handleFinish = (result) => {
  emit('onFinish', result)
}

// 处理拖拽开始
const handleDragStart = (e) => {
  e.preventDefault()
  isDragging.value = true

  // 记录初始鼠标位置和抽屉宽度
  const initialX = e.clientX
  const initialWidth = drawerWidth.value

  // 移动处理函数
  const handleMouseMove = (moveEvent) => {
    if (isDragging.value) {
      // 计算水平移动距离（向左为负，向右为正）
      const deltaX = moveEvent.clientX - initialX
      // 计算新宽度（向左拖动增加宽度）
      let newWidth = initialWidth - deltaX

      // 限制宽度范围
      newWidth = Math.max(props.minWidth, Math.min(props.maxWidth, newWidth))
      drawerWidth.value = newWidth
    }
  }

  // 拖拽结束处理函数
  const handleMouseUp = () => {
    isDragging.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
  }

  // 添加全局事件监听
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

// 清除可能的全局事件监听
onBeforeUnmount(() => {
  if (isDragging.value) {
    isDragging.value = false
    document.removeEventListener('mousemove', () => {})
    document.removeEventListener('mouseup', () => {})
  }
})

// 暴露方法给父组件
defineExpose({
  openDrawer,
  closeDrawer
})
</script>

<template>
  <!-- 悬浮按钮 -->
  <div
    class="chat-float-button"
    @click="handleFloatButtonClick"
    v-if="!drawerVisible && showFloatButton"
  >
    <div class="button-content">
      <div class="robot-icon">
        <img src="@/assets/images/robot-icon.jpg" alt="智能助手" />
      </div>
      <div class="text">
        <span>智能助手</span>
      </div>
    </div>
  </div>

  <!-- 侧边抽屉 -->
  <ElDrawer
    v-model="drawerVisible"
    :title="props.title"
    direction="rtl"
    :with-header="true"
    :size="drawerWidth"
    :destroy-on-close="false"
    :modal="true"
    :show-close="true"
    custom-class="chat-sidebar-drawer"
    :before-close="handleClose"
  >
    <!-- 拖拽手柄 -->
    <div
      class="drawer-resize-handle"
      @mousedown="handleDragStart"
      :class="{ dragging: isDragging }"
    ></div>

    <div class="chat-sidebar-container">
      <SimpleChat
        :api-key="props.apiKey"
        :api-base="props.apiBase"
        :placeholder="props.placeholder"
        :inputs="props.inputs"
        :welcome-message="props.welcomeMessage"
        @message-end="handleMessageEnd"
        @json-extracted="handleJsonExtracted"
        @onFinish="handleFinish"
        @closeElDrawer="handleClose"
        @getTaskID="handleGetTaskID"
        ref="simpleChatRef"
      />
    </div>
  </ElDrawer>
</template>

<style lang="scss" scoped>
.chat-float-button {
  position: fixed;
  right: 20px;
  bottom: 100px;
  z-index: 2000;
  cursor: pointer;
  border-radius: 16px;
  background-color: #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 12px;
  transition: all 0.3s;
  width: 80px;
  height: 110px;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
  }

  .button-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;

    .robot-icon {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      overflow: hidden;
      margin-bottom: 8px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .text {
      text-align: center;
      font-size: 14px;
      color: #409eff;
      font-weight: 500;
      line-height: 1.2;
    }
  }
}

:deep(.chat-sidebar-drawer) {
  .el-drawer__header {
    margin-bottom: 0;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: 600;
    color: #303133;
  }

  .el-drawer__body {
    padding: 0;
    overflow: hidden;
    position: relative;
    /* 为拖拽手柄定位 */
  }
}

.drawer-resize-handle {
  position: absolute;
  left: 0;
  top: 0;
  width: 8px;
  height: 100%;
  cursor: ew-resize;
  background-color: transparent;
  z-index: 10;

  &:hover,
  &.dragging {
    background-color: rgba(64, 158, 255, 0.1);
  }

  &:before {
    content: '';
    position: absolute;
    left: 3px;
    top: 50%;
    height: 30px;
    width: 2px;
    margin-top: -15px;
    background-color: #dcdfe6;
    border-radius: 1px;
  }

  &:hover:before,
  &.dragging:before {
    background-color: #409eff;
  }
}

.chat-sidebar-container {
  height: 100%;
  overflow: hidden;
}
</style>
